package com.hserver.deploy.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.hserver.deploy.bean.Msg;
import com.hserver.deploy.service.IndexService;
import top.hserver.core.interfaces.WebSocketHandler;
import top.hserver.core.ioc.annotation.Autowired;
import top.hserver.core.ioc.annotation.WebSocket;
import top.hserver.core.server.context.ConstConfig;
import top.hserver.core.server.handlers.Ws;

import java.util.HashMap;
import java.util.Map;

@WebSocket("/ws")
public class DataWebSocket implements WebSocketHandler {

    @Autowired
    private IndexService indexService;

    final static Map<String,Ws> wsMap=new HashMap<>();

    @Override
    public void onConnect(Ws ws) {
        System.out.println("有人连接了");
    }

    @Override
    public void onMessage(Ws ws) {
        String res = ws.getMessage();
        JsonNode jsonNode = null;
        try {
            jsonNode = ConstConfig.OBJECT_MAPPER.readTree(res);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String type=jsonNode.get("type").asText();
        if (type==null){
            return;
        }
        String uuid=jsonNode.get("uuid").asText();
        wsMap.put(uuid,ws);

        switch (type){
            case "showLog":
                try{
                   String sa= indexService.showLog(uuid);
                    System.out.println(sa);
                    ws.send(ConstConfig.OBJECT_MAPPER.writeValueAsString(new Msg(uuid,"showLog",sa)));
                }catch (Exception e){
                    ws.getCtx().close();
                }
                break;
        }

    }

    public static void sendMsg(String uuid,String msg){
        Ws ws=wsMap.get(uuid);
        if (ws!=null){
            ws.send(msg);
        }
    }

    @Override
    public void disConnect(Ws ws) {
        wsMap.remove(ws.getUid());
    }
}
